package acheng1314.cn.a3dbuild2.view.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.TextView;

import com.acheng.achengutils.mvp.view.BaseActivity;
import com.acheng.achengutils.utils.SPHelper;
import com.acheng.achengutils.widgets.AppUpdateDialog;
import com.acheng.achengutils.widgets.MustDoThingDailog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import acheng1314.cn.a3dbuild2.MyApplication;
import acheng1314.cn.a3dbuild2.R;
import acheng1314.cn.a3dbuild2.bean.LoginBean;
import acheng1314.cn.a3dbuild2.bean.ModelUrlBean;
import acheng1314.cn.a3dbuild2.hostApi.MyApi;
import acheng1314.cn.a3dbuild2.view.activity.presenter.LoginActivityPresenter;
import acheng1314.cn.a3dbuild2.view.activity.viewcontroller.LoginActivityViewController;
import acheng1314.cn.a3dbuild2.widgets.MyProgressDialog;

/**
 * Created by pc859107393 on 2016/9/12 0012.
 */
public class LoginActivity extends BaseActivity<LoginActivityPresenter, LoginActivityViewController> implements LoginActivityViewController {

    private View mBt_login;
    private TextView mEt_username;  //用户名
    private TextView mEt_password;  //密码s


    final private int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 124;
    private AppUpdateDialog appPermission;
    private MyProgressDialog myProgressDialog;

    @Override
    protected LoginActivityPresenter initPresenter() {
        return new LoginActivityPresenter(this);
    }

    @Override
    protected void initEvent() {
        mBt_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyApplication.getInstance().outLog(TAG, "MDZZ");
                mPresenter.doLogin(mEt_username.getText().toString(), mEt_password.getText().toString());


            }
        });
    }

    @Override
    protected void initView() {
        MyApplication.getInstance().addActivity(this);
        mEt_username = (TextView) findViewById(R.id.mEt_username);
        mEt_password = (TextView) findViewById(R.id.mEt_password);
        mBt_login = findViewById(R.id.mBt_login);
    }

    @Override
    protected void doOther() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            List<String> permissionsNeeded = new ArrayList<String>();

            final List<String> permissionsList = new ArrayList<String>();
            if (!addPermission(permissionsList, Manifest.permission.WRITE_EXTERNAL_STORAGE))
                permissionsNeeded.add("手机存储空间");
            if (!addPermission(permissionsList, Manifest.permission.READ_PHONE_STATE))
                permissionsNeeded.add("获取手机状态");
            if (!addPermission(permissionsList, Manifest.permission.CAMERA))
                permissionsNeeded.add("手机相机");
            if (!addPermission(permissionsList, Manifest.permission.ACCESS_COARSE_LOCATION))
                permissionsNeeded.add("手机位置");
//            if (!addPermission(permissionsList, Manifest.permission.WRITE_SETTINGS))
//                permissionsNeeded.add("手机设置");

            if (permissionsList.size() > 0) {
                if (permissionsNeeded.size() > 0) { //待申请的权限列表
                    // Need Rationale
                    String message = "你必须允许本APP使用：" + permissionsNeeded.get(0);
                    for (int i = 1; i < permissionsNeeded.size(); i++)
                        message = message + ", " + permissionsNeeded.get(i);
                    showMessageOKCancel(message,
                            new DialogInterface.OnClickListener() {
                                @TargetApi(Build.VERSION_CODES.M)
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                                            REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
                                }
                            });
                    return;
                }
                requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                        REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
            }
        }
        super.doOther();
    }

    private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
        new AlertDialog.Builder(this)
                .setMessage(message)
                .setPositiveButton("允许", okListener)
                .setNegativeButton("拒绝", null)
                .create()
                .show();
    }

    private boolean addPermission(List<String> permissionsList, String permission) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
                permissionsList.add(permission);
                if (!shouldShowRequestPermissionRationale(permission))
                    return false;
            }
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS: {
                Map<String, Integer> perms = new HashMap<String, Integer>();
                // Initial
                perms.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
                perms.put(Manifest.permission.READ_PHONE_STATE, PackageManager.PERMISSION_GRANTED);
                perms.put(Manifest.permission.CAMERA, PackageManager.PERMISSION_GRANTED);
                perms.put(Manifest.permission.ACCESS_COARSE_LOCATION, PackageManager.PERMISSION_GRANTED);
                // Fill with results
                for (int i = 0; i < permissions.length; i++)
                    perms.put(permissions[i], grantResults[i]);
                // Check for ACCESS_FINE_LOCATION
                if (perms.get(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
                        && perms.get(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED
                        && perms.get(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
                        && perms.get(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    //经过用户授权，获得所有权限
                    if (appPermission != null) {
                        appPermission = null;
                    }
                    // All Permissions Granted
                } else {    //未得到用户授权
                    // Permission Denied
                    appPermission = new AppUpdateDialog(AppUpdateDialog.IMPORTANT, "一些权限未被允许，请在设置中授权!", getContext(), new AppUpdateDialog.NeedDoThing() {
                        @Override
                        public void mustDoThing() {
                            Uri packageURI = Uri.parse("package:" + getPackageName());
                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                            startActivity(intent);
                        }
                    });
                }
            }
            break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        doOther();
    }

    @Override
    protected int setLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public void showDailog(String msg) {
        new MustDoThingDailog("提示", msg, getContext(), new MustDoThingDailog.NeedDoThing() {
            @Override
            public void mustDoThings() {

            }
        });
    }

    @Override
    public void showProgressD() {
        if (null == myProgressDialog)
            myProgressDialog = new MyProgressDialog("登陆", "正在登录···", getContext());
        else
            myProgressDialog.show();
    }

    @Override
    public void disProgressD() {
        if (null != myProgressDialog)
            myProgressDialog.dismiss();
    }

    @Override
    public void openHome(LoginBean bean) {

        SPHelper.setString(getContext(), getContext().getString(R.string.user), getContext().getString(R.string.username), mEt_username.getText().toString());
        SPHelper.setString(getContext(), getContext().getString(R.string.user), getContext().getString(R.string.password), mEt_password.getText().toString());
        SPHelper.setString(getContext(), getContext().getString(R.string.user), getContext().getString(R.string.userId), bean.getResult().getUserId());
        SPHelper.setString(getContext(), getContext().getString(R.string.user), getContext().getString(R.string.token), bean.getResult().getToken());

        Intent startActivity = new Intent(getContext(), AppWebActivity.class);
        String urlStr = MyApi.MapApi + "?uid=" + bean.getResult().getUserId() + "&kw=&token=" + bean.getResult().getToken();
        ModelUrlBean urlBean = new ModelUrlBean();
        urlBean.setUid(bean.getResult().getUserId());
        urlBean.setToken(bean.getResult().getToken());
        urlBean.setLatitu("0.0");
        urlBean.setLongit("0.0");
        startActivity.putExtra(getString(R.string.url), urlStr);
        startActivity.putExtra("urlBean", urlBean);
        startActivity(startActivity);

        finish();
    }
}
